import os
from ..utils.log import logger
import json
from ..utils.database import InferSessionLocal

import os
import threading
from queue import Queue
from ..model.infer import ScpJob, Lot

from .. import async_msg
import threading
from ..job.panel_job import PanelJob
from datetime import datetime, timedelta


root_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


class InferJob(PanelJob):
    """
    自动推理
    """

    def __init__(self):

        self.queue = Queue()
        self.stop = threading.Event()
        
        super().__init__()  # 正确调用父类的 __init__ 方法


    def add_lot_dir(self, job_code):
        with InferSessionLocal() as session:
            scp_job = session.query(ScpJob).filter(ScpJob.job_code==job_code).first()

            if not scp_job:
                return
            self.queue.put(job_code)
            
            # 推理排队中
            scp_job.status = '5'
            session.commit()


    def run(self):
        logger.info("启动自动推理任务")
        while not self.stop.is_set():
            try:
                job_code = self.queue.get(timeout=10)
            except Exception as e:
                continue

            logger.info(f"取到推理任务的 job_code:{job_code}")
          
            with InferSessionLocal() as session:
                scp_job = session.query(ScpJob).filter(ScpJob.job_code==job_code).first()

                if not scp_job:
                    continue

                if scp_job.last_flag == '1':
                    is_last = True
                else:
                    is_last = False

                material_code = scp_job.material_code
                lot_code = scp_job.lot_code
                aoi_code = scp_job.aoi_code

                lot = session.query(Lot).filter(Lot.lot_code==lot_code).first()
                lot_dirpath = lot.dir_path
                
                scp_timestamp = scp_job.start_datetime.strftime("%Y%m%d%H%M") + "_" + scp_job.end_datetime.strftime("%Y%m%d%H%M")
                scp_dirpath = os.path.join(lot_dirpath, scp_timestamp)

                msg = f'Scp Job {scp_job.start_datetime} ~ {scp_job.end_datetime} 推理排队中'
                logger.info(msg)
                scp_job.status = '6'

                session.commit()

                try:
                    msg = f'Scp Job {scp_job.start_datetime} ~ {scp_job.end_datetime} 开始推理'
                    async_msg(msg)
                    logger.info(msg)

                    self.detect_lot(scp_dirpath, material_code, lot_code, aoi_code, is_last)

                    # scp 推理完
                    msg = f'Scp Job {scp_job.start_datetime} ~ {scp_job.end_datetime} 推理已完成'
                    async_msg(msg)
                    logger.info(msg)

                    scp_job.status = '8'

                    # session.refresh(scp_job)
                    scp_job = session.query(ScpJob).filter(ScpJob.job_code==job_code).first()

                    logger.info(f"刷新后的 scp_job 是否是最后一个：{scp_job.last_flag}, {job_code}")
                    
                    if scp_job.last_flag == '1':
                        lot = session.query(Lot).filter(Lot.lot_code==lot_code).first()
                        lot.status = '1'

                    session.commit()

                except Exception as e:
                    msg = f'Scp Job {scp_job.start_datetime} ~ {scp_job.end_datetime} 推理出错: {e}'
                    async_msg(msg)
                    logger.error(msg)


        self.queue.queue.clear()
        logger.info("自动推理任务停止")

        lot.status = '1'
        lot.end_time = datetime.utcnow() + timedelta(hours=8)
        session.commit()
            
        
    

# =============jduan lot====================
infer_job = InferJob()